/*
 * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin
 * Systems and Internet Infrastructure Security Laboratory
 *
 * Author: Damien Octeau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package edu.psu.cse.siis.ic3.db;

import java.sql.SQLException;

public class AppInfoTable extends Table {
  private static final String INSERT = "INSERT INTO \"AppInfo\" (app_pkgname) VALUES (?)";
  private static final String FIND = "SELECT id FROM \"AppInfo\" WHERE app_pkgname = ?";

  public int insert(String app_pkgname, int download_number) throws SQLException {
    int id = find(app_pkgname, download_number);
    findStatement.close();
    if (id != NOT_FOUND) {
      return id;
    }
    return forceInsert(app_pkgname, download_number);
  }

  public int forceInsert(String app_pkgname, int download_number) throws SQLException {
    if (insertStatement == null || insertStatement.isClosed()) {
      insertStatement = getConnection().prepareStatement(INSERT + " returning id;");
    }
    insertStatement.setString(1, app_pkgname);
    // if (download_number == NOT_FOUND) {
    // insertStatement.setNull(2, Types.INTEGER);
    // } else {
    // insertStatement.setInt(2, 0);
    // }

    // ResultSet last_updated_person = insertStatement.executeQuery();
    // int result;
    // if (last_updated_person.next()) {
    // result = last_updated_person.getInt(1);
    //
    // } else {
    // result = NOT_FOUND;
    // }
    return processIntFindQuery(insertStatement);
    // if (insertStatement.executeUpdate() == 0) {
    // return NOT_FOUND;
    // }
    // return findAutoIncrement();
  }

  public int find(String app_pkgname, int download_number) throws SQLException {
    String formatArg = (download_number == NOT_FOUND) ? "IS" : "=";
    findStatement = getConnection().prepareStatement(String.format(FIND, formatArg));
    findStatement.setString(1, app_pkgname);
    // if (download_number == NOT_FOUND) {
    // findStatement.setNull(2, Types.INTEGER);
    // } else {
    // findStatement.setInt(2, 0);
    // }
    return processIntFindQuery(findStatement);
  }
}
